package com.durian.base.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;

import com.durian.BaseApp;

import java.lang.reflect.Method;

/**
 * 说明：软键盘工具类
 * <p>
 * 作者：fanly
 * <p>
 * 类型：Class
 * <p>
 * 时间：2016/8/18 15:37
 * <p>
 * 版本：version 1.0
 */
public class KeyBoardUtils {

    private static int rootViewVisibleHeight;/*纪录根视图的显示高度*/

    public interface OnSoftKeyboardStateChangedListener {
        void onSoftKeyboardShow(int height);
        void onSoftKeyboardHide(int height);
    }

    /**
     * 说明：强制显示软键盘
     * @param et
     */
    public static void showSoftInput(final View et) {
        if (et != null) {
            et.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (et != null){
                        et.requestFocus();
                        et.findFocus();
                        InputMethodManager inputManager = (InputMethodManager) et
                                .getContext()
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputManager.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
                    }
                }
            },300);
        }
    }

    /**
     * 说明：强制隐藏软键盘
     */
    public static void hiddenSoftInput(Activity activity) {
        if(activity==null)return;
        final View v = activity.getWindow().peekDecorView();
        hiddenSoftInput(v);
    }

    /**
     * 说明：强制隐藏软键盘
     */
    public static void hiddenSoftInput(View view) {
        if (view != null && view.getWindowToken() != null) {
            InputMethodManager imm = (InputMethodManager) BaseApp.getApp().getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 获取软键盘高度
     * @param paramActivity
     * @return
     */
    public static int getKeyboardHeight(Activity paramActivity) {
        int height = getScreenHeight(paramActivity) - UIUtils.getStatusBarHeight(paramActivity)
                - getAppHeight(paramActivity);
        return height;
    }

    /**
     * 屏幕分辨率高
     * @param paramActivity
     * @return
     */
    public static int getScreenHeight(Activity paramActivity) {
        Display display = paramActivity.getWindowManager().getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        return metrics.heightPixels;
    }

    /**
     * 可见屏幕高度
     * @param paramActivity
     * @return
     */
    public static int getAppHeight(Activity paramActivity) {
        Rect localRect = new Rect();
        paramActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
        return localRect.height();
    }

    /**
     * 键盘是否在显示
     * @param paramActivity
     * @return
     */
    public static boolean isKeyBoardShow(Activity paramActivity) {
        int height = getScreenHeight(paramActivity) - UIUtils.getStatusBarHeight(paramActivity)
                - getAppHeight(paramActivity);
        return height != 0;
    }

    public static void setOnGlobalLayoutListener(final Activity activity, final OnSoftKeyboardStateChangedListener listener){
        if (listener == null || activity == null)return;
        final View rootView = activity.getWindow().getDecorView();
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                /*获取当前根视图在屏幕上显示的大小*/
                Rect r = new Rect();
                rootView.getWindowVisibleDisplayFrame(r);
                int visibleHeight = r.height();
                if (rootViewVisibleHeight == 0) {
                    rootViewVisibleHeight = visibleHeight;
                    return;
                }
                /*根视图显示高度没有变化，可以看作软键盘显示／隐藏状态没有改变*/
                if (rootViewVisibleHeight == visibleHeight) {
                    return;
                }
                /*根视图显示高度变小超过200，可以看作软键盘显示了*/
                if (rootViewVisibleHeight - visibleHeight > 200) {
                    if (listener != null) {
                        listener.onSoftKeyboardShow(rootViewVisibleHeight - visibleHeight);
                    }
                    rootViewVisibleHeight = visibleHeight;
                    return;
                }
                /*根视图显示高度变大超过200，可以看作软键盘隐藏了*/
                if (visibleHeight - rootViewVisibleHeight > 200) {
                    if (listener != null) {
                        listener.onSoftKeyboardHide(visibleHeight - rootViewVisibleHeight);
                    }
                    rootViewVisibleHeight = visibleHeight;
                    return;
                }
            }
        });
    }

    //获取虚拟按键的高度
    public static int getNavigationBarHeight(Context context) {
        int result = 0;
        if (hasNavBar(context)) {
            try {
                Resources res = context.getResources();
                int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
                if (resourceId > 0) {
                    result = res.getDimensionPixelSize(resourceId);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 检查是否存在虚拟按键栏
     *
     * @param context
     * @return
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static boolean hasNavBar(Context context) {
        boolean hasNavBar = false;
        try {
            Resources res = context.getResources();
            int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
            if (resourceId != 0) {
                boolean hasNav = res.getBoolean(resourceId);
                // check override flag
                String sNavBarOverride = getNavBarOverride();
                if ("1".equals(sNavBarOverride)) {
                    hasNav = false;
                } else if ("0".equals(sNavBarOverride)) {
                    hasNav = true;
                }
                hasNavBar = hasNav;
            } else { // fallback
                hasNavBar = !ViewConfiguration.get(context).hasPermanentMenuKey();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            return hasNavBar;
        }
    }

    /**
     * 判断虚拟按键栏是否重写
     *
     * @return
     */
    private static String getNavBarOverride() {
        String sNavBarOverride = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                Class c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sNavBarOverride;
    }
}
